package cn.my.springHDFS.service;

import cn.my.springHDFS.domain.AdminUser;
import cn.my.springHDFS.domain.SpiderStatus;
import cn.my.springHDFS.domain.User;
import cn.my.springHDFS.repository.UserRepository;
import cn.my.springHDFS.util.HDFS_Util;
import cn.my.springHDFS.util.ToolUtil;
import com.mongodb.WriteResult;
import org.apache.hadoop.conf.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Leo on 2017/7/3.
 * 用户实现类
 */
@Repository
public class UserServiceImpl {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserHistoryServiceImpl userHistoryService;

    /**
     * 通过用户账号查询用户
     * @param account
     * @return
     */
    public User findByuserAccount(String account){
        return userRepository.findByAccount(account);
    }

    /**
     * 注册用户
     * @param account
     * @param emailAddr
     * @param password
     * @return
     */
    public boolean addUser(String account, String emailAddr, String password){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

        //封装User类
        User u = new User();
        u.setAccount(account);
        u.setUsername(account);
        u.setEmail(emailAddr);
        u.setPassword(password);
        u.setFrozen(false);
        u.setUserFolderRoot("/" + account);
        u.setUserLevel("ROLE_USER");
        u.setRegisterTime(df.format(new Date()));
        u.setLoginTime("");
        u.setLogoutTime("");

        try{
            //实例化ToolUtil, HDFS_Util, HDFS Configuration, 创建文件夹
            HDFS_Util hdfs_util = new HDFS_Util();
            ToolUtil toolUtil = new ToolUtil();
            List<Object> objectList = toolUtil.ipSwitch(SpiderStatus.getIsActive());
            Configuration conf = (Configuration) objectList.get(0);
            if (hdfs_util.CreatDir(u.getUserFolderRoot(), conf, u.getUsername())){
                //保存用户对象
                userRepository.save(u);
                return true;
            }
            return false;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 验证用户是否存在
     * @param account
     * @return
     */
    public boolean validateUser(String account){
        //u为空则为false即不存在,u不为空则true即存在
        User u = userRepository.findByAccount(account);
        if (u == null){
            return false;
        }
        return true;
    }

    /**
     * 验证用户邮箱是否存在
     * @param emailAddr
     * @return
     */
    public boolean validateEmail(String emailAddr){
        //u为空则为false即不存在,u不为空则true即存在
        User u = userRepository.findByEmail(emailAddr);
        if (u == null){
            return false;
        }
        return true;
    }

    /**
     * 用户登录状态
     * @param user
     * @param LogoutOrIn
     * @return
     */
    public boolean userLoginInfo(User user, Boolean LogoutOrIn, HttpServletRequest httpServletRequest){
        Query query = Query.query(Criteria.where("account").is(user.getAccount()));
        Update update = new Update();
        try{
            if (!LogoutOrIn){
                update.set("loginTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                boolean isUpsertLogin = mongoTemplate.upsert(query, update, User.class).wasAcknowledged();
                boolean loginLogger = userHistoryService.addUserLoginLogger(user, httpServletRequest);
                return !isUpsertLogin && loginLogger;
            }
            else {
                update.set("logoutTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                boolean isUpsertLogout = mongoTemplate.upsert(query, update, User.class).wasAcknowledged();
                boolean logoutLogger = userHistoryService.addUserLogoutLogger(user, httpServletRequest);
                return !isUpsertLogout && logoutLogger;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

}
